
package com.kweative.lingua.server;

import com.kweative.lingua.server.transport.Transport;
import java.io.IOException;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class Server {
    private Stack<Thread> appThreads = new Stack<Thread>();
    public void start() {
        
        for(Application app:Config.instance().applications().values()) {
            Thread t = new Thread(app);
            t.start();
            appThreads.push(t);
        }
        for(Transport transport:TransportPool.instance().transports()) {
            transport.listen();
        }
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                Server.this.stop();
            }
        });
    }
    public void stop() {
        for(Transport transport:TransportPool.instance().transports()) {
            transport.close();
        }
        String oldHomeDir = System.getProperty("user.dir");
        for(Application app:Config.instance().applications().values()) {
            //Attempt to change homedir
            System.setProperty("user.dir",app.getHomedir().getAbsolutePath());
            try {
                Runtime.getRuntime().exec(String.format("cd \"%s\"",app.getHomedir().getAbsolutePath()));
            } catch (IOException ex) {
                Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
            }
            app.onApplicationUnload();
        }
        System.setProperty("user.dir",oldHomeDir);
        try {
            Runtime.getRuntime().exec(String.format("cd \"%s\"",oldHomeDir));
        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        for(Thread t:appThreads) {
            if (t.isAlive() && !t.interrupted())
                t.interrupt();
        }
    }
}
